/// ITT of daily regression, barchart, table, and heterogeneity 

********************************************************************************
* Get data
use "data/pseudodata/userlevel_pseudodata.dta", clear

*replace bound 1 to 100 for ITT graphs
foreach var of varlist bound anybound* threemonther threemonthcrer {
	replace `var' = 100 if `var'==1
}

*** Table 2. ITT 
eststo clear

label variable daily "Pay-as-you-go"
label variable daysnonzeroreserve90 "Days with coverage"

local outcomes ///
"bound daysnonzeroreserve90 totdayscoverage90 threemonther anybound7 daysnonzeroreserve90cr totdayscoverage90cr threemonthcrer"

local i=1		
foreach var of varlist `outcomes' {
	eststo est`i':  quietly reg `var' daily, r
	quietly summ `var'
	estadd scalar mean = r(mean)
	local i=`i'+1
}

esttab est1 est2 est3 est4 using "output/tables/ITT daily contract all.tex", ///
prehead("\begin{tabular}{lP{1.7cm}P{1.7cm}P{1.7cm}P{1.7cm}} \hline\hline") ///
posthead("\hline \\ \multicolumn{5}{c}{\textit{A. Insurance through experiment}} \\\\[-1ex]") ///
fragment ///
replace label nomtitle unstack collabels(, none) ///
stats(N mean, fmt(%12.3gc) labels("N" "Mean")) ///
cells(b(fmt(2)) se(par fmt(2)) p(par([ ]) fmt(3))) /// 
	mgroups("Take-up" "Days with coverage" "Days insured" "Insured end of study", ///
		pattern(1 1 1 1))

esttab est5 est6 est7 est8 using "output/tables/ITT daily contract all.tex", ///
posthead("\hline \\ \multicolumn{5}{c}{\textit{B. Any insurance}} \\\\[-1ex]") ///
fragment append ///
nomtitles nomtitle nonumbers nolines ///
prefoot("\hline") postfoot("\hline\hline \end{tabular}") ///
label unstack collabels(, none) ///
stats(N mean, fmt(%12.3gc) labels("N" "Mean")) ///
cells(b(fmt(2)) se(par fmt(2)) p(par([ ]) fmt(3))) 
	
*** Table 4. ITT interacted with driving history
*generate interacting variable
gen neveregm = nevereg
replace nevereg = nevereg*100
label variable nevereg "No regular policy history"
label variable neveregm "No regular policy history"
local ints = "nevereg"

eststo clear

local i=1
foreach int of local ints {
	local outcomes ///
	"bound anybound7 totdayscoverage90 daysnonzeroreserve90cr"
	foreach var of varlist `outcomes' {
		eststo est`i':  reg `var' i.daily##i.`int'm, r
		quietly summ `int', det
		if inlist(`i', 1,5,9) estadd scalar mean = r(mean)
		if inlist(`i', 1,5,9) estadd scalar n = r(N)
		local i = `i'+1
	}			
	local i4=`i'-4
	local i3=`i'-3
	local i2=`i'-2
	local i1=`i'-1
}

esttab est1 est2 est3 est4 using "output/tables/ITT daily contract no prior coverage.tex", tex ///
	prehead("\begin{tabular}{lP{1.7cm}P{1.7cm}P{1.7cm}P{1.7cm}} \hline\hline") ///
	posthead("\hline") ///
	fragment label ///
	replace nomtitle gaps noomitted nobaselevels ///
	prefoot("\hline") postfoot("\hline\hline \end{tabular}") ///
	stats(n mean, fmt(%11.0gc %12.3gc) labels("N" "No regular policy history")) ///
	cells(b(fmt(2) label("\phantom{")) se(par fmt(2) label(" ")) ///
		p(par([ ]) fmt(3) label("}\vspace{-.9mm}"))) ///
	varwidth(25) wrap   /// 
	mgroups("Take-up" "Days with coverage" "Days insured" "Insured end of study", ///
		pattern(1 1 1 1))
		
		
********************************************************************************
*** ITT barcharts

*** hugo and any insurance outcomes
* save regression output and reshape to present means as bar charts
* save confidence interval of coefficient for mean of treatment group in bar charts
preserve
	local outcomes "bound anybound7 daysnonzeroreserve90 daysnonzeroreserve90cr"
	keep id daily bound anybound7 daysnonzeroreserve90 daysnonzeroreserve90cr

	foreach var of varlist `outcomes' {
		rename `var' val`var'
	}
	reshape long val, i(id daily) j(type) string

	gen lcl = .
	gen ucl = .
	foreach outcome of local outcomes {
		reg val daily if type=="`outcome'", r
		local lcl = _b[_cons] + _b[daily] - invttail(e(df_r), .025) * _se[daily]
		local ucl = _b[_cons] + _b[daily] + invttail(e(df_r), .025) * _se[daily]
		replace lcl = `lcl' if type=="`outcome'" & daily==1
		replace ucl = `ucl' if type=="`outcome'" & daily==1
	}

	collapse (mean) meanval = val (sd) sdval = val (count) n=val, by(daily type lcl ucl)

	gen numtype = .
	replace numtype = 1 if type == "daysnonzeroreserve90"
	replace numtype = 2 if type == "daysnonzeroreserve90cr"

	gen dtype = .
	replace dtype = daily if numtype == 1
	replace dtype = daily + 3 if numtype == 2

	local j=1
	foreach outcome of local outcomes {
		forval i=0/1 {
			summ meanval if type=="`outcome'" & daily==`i'
			local m`j' = round(`r(mean)',.01)
			if `m`j''>10 local m`j' = round(`m`j'',.1)
			local m`j'_di: di %9.1f `m`j''
			di "`m`j'_di'"
			local j=`j'+1
		}
	}

	twoway 	(bar meanval dtype if daily == 0 & !mi(numtype), ///
				text(`=`m5'+.1' -.15 "`m5_di'", place(n)) ///
				text(`=`m7'+.1' 2.85 "`m7_di'", place(n))) /// 
			(bar meanval dtype if daily == 1 & !mi(numtype), ///
				text(`=`m6'+.1' 1.1 "`m6_di'", place(n)) ///
				text(`=`m8'+.1' 4.1 "`m8_di'", place(n))) ///
			(rcap lcl ucl dtype if !mi(numtype), col("185 217 235")), ylabel(0(6)30) ///
			legend(size(med) order(1 "Traditional" 2 "Pay-as-you-go" 3 "95% CI") pos(11) ring(0)) ///
				xlabel(0.5 "Hugo" 3.5 "Any insurance") ///
				ytitle("") xtitle("") ///
				subtitle("Days with coverage", position(11) span)
	graph save two.gph, replace

	replace numtype = .
	replace numtype = 1 if type == "bound"
	replace numtype = 2 if type == "anybound7"

	replace dtype = .
	replace dtype = daily if numtype == 1
	replace dtype = daily + 3 if numtype == 2

	twoway 	(bar meanval dtype if daily == 0, ///
				text(`=`m1'+.1' -.15 "`m1_di'", place(n)) ///
				text(`=`m3'+.1' 2.85 "`m3_di'", place(n))) ///
			(bar meanval dtype if daily == 1, ///
				text(`=`m2'+.1' 1.1 "`m2_di'", place(n)) ///
				text(`=`m4'+.1' 4.1 "`m4_di'", place(n))) ///
			(rcap lcl ucl dtype, col("185 217 235")), ///
				ylabel(0 "0%" 10 "10%" 20 "20%" 30 "30%") ///
			legend(off) ///
			xlabel(0.5 "Hugo" 3.5 "Any insurance") ytitle("") xtitle("") ///
			subtitle("Take-up (%)", position(11) span)
	graph save one.gph, replace
			
	graph combine one.gph two.gph, iscale(0.9) imargin(medsmall)
	graph export "output/figures/ITT daily contract bars all.pdf", replace

	erase one.gph
	erase two.gph
restore
